package es.udc.fic.hamNeggs.web;

import org.apache.log4j.Logger;

import es.udc.fic.hamNeggs.dao.InputSprint;
import es.udc.fic.hamNeggs.dao.InputUser;
import es.udc.fic.hamNeggs.dao.InputUserStory;
import es.udc.fic.hamNeggs.manager.ProjectManager;
import es.udc.fic.hamNeggs.manager.SprintManager;
import es.udc.fic.hamNeggs.manager.UserStoriesCommentManager;
import es.udc.fic.hamNeggs.manager.UserStoriesManager;
import es.udc.fic.hamNeggs.pojo.Sprint;
import es.udc.fic.hamNeggs.pojo.UserStories;
import es.udc.fic.hamNeggs.pojo.UserStories.State;
import es.udc.fic.hamNeggs.pojo.Works;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Servlet implementation class ServletDetails
 */
public class SprintDetails extends HttpServlet {
    private static final long   serialVersionUID = 1L;
    private final static Logger LOG              = Logger.getLogger(SprintDetails.class.getName());

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SprintDetails() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);
        final Long myProject = (Long) session.getAttribute("project");
        final Long myUser = (Long) session.getAttribute("user");

        final ProjectManager prjmng = new ProjectManager();

        final ArrayList<InputUser> users = new ArrayList<InputUser>();

        for (final Works w : prjmng.getProject(new Long(myProject)).getWorker()) {
            if (w.getUser().getId().doubleValue() != myUser.doubleValue()) {
                final InputUser u = new InputUser();
                u.setUser(w.getUser());
                users.add(u);
            }
        }

        request.setAttribute("users", users);

        final ArrayList<InputUserStory> usts = new ArrayList<InputUserStory>();
        for (final UserStories ust : prjmng.getProject(myProject).getUserStories()) {
            final InputUserStory iust = new InputUserStory();
            iust.setUserStory(ust);
            if (ust.getSprint() == null && ust.getState() == State.Created) {
                usts.add(iust);
            }
        }
        request.setAttribute("userStories", usts);

        if ((request.getParameter("id") != null && request.getParameter("id") != "") || (request.getAttribute("sprid") != null && request.getAttribute("sprid").toString() != "")) {
            final SprintManager sprmng = new SprintManager();
            Sprint spr = null;
            if (request.getParameter("id") != null)
                spr = sprmng.getSprint(new Long(request.getParameter("id")));
            if (request.getAttribute("sprid") != null)
                spr = sprmng.getSprint(new Long(request.getAttribute("sprid").toString()));
            final InputSprint selectSprint = new InputSprint();
            selectSprint.setSprint(spr);
            request.setAttribute("selectSprint", selectSprint);
            sprmng.close();
        }
        prjmng.close();
        request.getRequestDispatcher("/sprint_detail.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final HttpSession session = request.getSession(true);

        final Long myProject = (Long) session.getAttribute("project");

        final SprintManager sprmng = new SprintManager();
        final UserStoriesManager ustmng = new UserStoriesManager();
        final UserStoriesCommentManager cmtmng = new UserStoriesCommentManager();
        final ProjectManager prjmng = new ProjectManager();

        try {
            switch (request.getParameter("action")) {
                case "Add":
                    final InputSprint sprint = new InputSprint();
                    final String[] listUst = request.getParameterValues("userStories");

                    final ArrayList<String> userStories = new ArrayList<String>();
                    if (listUst != null)
                        for (final String a : listUst)
                            userStories.add(a);

                    sprint.setUserStories(userStories);

                    if (request.getParameter("name") != null)
                        sprint.setName(request.getParameter("name"));
                    if (request.getParameter("dateStart") != null)
                        sprint.setDateStart(request.getParameter("dateStart"));
                    if (request.getParameter("dateEnd") != null)
                        sprint.setDateEnd(request.getParameter("dateEnd"));

                    final Sprint newSprint = sprint.toSprint();

                    if (newSprint != null) {
                        newSprint.setProject(prjmng.getProject(myProject));
                        sprmng.saveSprint(newSprint);
                        final List<UserStories> stories = newSprint.getProposedTasks();

                        for (final UserStories u : stories) {
                            u.setSprint(newSprint);
                            ustmng.updateUserStories(u);
                        }
                    }
                    break;
                case "Update":
                    final Sprint sprintu = sprmng.getSprint(new Long(request.getParameter("sprid")));

                    if (request.getParameter("name") != null)
                        sprintu.setName(request.getParameter("name"));
                    if (request.getParameter("dateStart") != null)
                        sprintu.setDateStart(Date.valueOf(request.getParameter("dateStart")));
                    if (request.getParameter("dateEnd") != null)
                        sprintu.setDateEnd(Date.valueOf(request.getParameter("dateEnd")));

                    final String[] listUstr = request.getParameterValues("userStories");

                    if (listUstr != null) {
                        for (final String usts : listUstr) {
                            final UserStories u = ustmng.getUserStories(new Long(usts));
                            u.setSprint(sprintu);
                            ustmng.updateUserStories(u);
                        }
                    }
                    sprmng.updateSprint(sprintu);
                    break;
                default:
                    break;

            }
        } catch (Exception e) {
            String error = "[";
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()) {
                final String paramName = names.nextElement();
                final String paramValue = request.getParameter(paramName);
                error = error.concat(paramName + ":" + paramValue + "|");
            }
            error = error.concat("]");
            LOG.error("Error while executing action: " + request.getParameter("action")
                    + ", with params: " + error + "\n"
                    , e);
        }

        ustmng.close();
        sprmng.close();
        cmtmng.close();
        prjmng.close();

        request.setAttribute("sprid", request.getParameter("sprid"));
        doGet(request, response);
    }

}
